﻿using System;
using System.Collections.Generic;
using System.Text;

namespace gChartSharp
{
    public class DataSeriesParam : ParamBase<float[]>, IRenderable
    {
        public override string Name { get { return "chd"; } }


        public EncodingType EncodingType { get; set; }


        public DataSeriesParam()
        {
            EncodingType = EncodingType.Text;
        }

        public override string Render()
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("&{0}={1}:", Name, (char)EncodingType);

            if (Params.Count > 0)
            {
                Params.ForEach((float[] dataSet) =>
                    {
                        // Simple and Extended encoded data sets are delimited with a comma
                        if (this.EncodingType == EncodingType.Simple || EncodingType == EncodingType.Extended)
                        {
                            IEncoder encoder = EncoderFactory.GetEncoderByType(EncodingType);

                            foreach (float f in dataSet)
                                sb.Append(String.Format("{0}", encoder.Encode(f)));

                            // add delimiter
                            sb.Append(",");
                        }
                        // Text encoded data sets are delimited with a pipe, each data point is separated by a comma
                        else
                        {
                            IEncoder encoder = EncoderFactory.GetEncoderByType(EncodingType);

                            foreach (float f in dataSet)
                                sb.AppendFormat("{0},", encoder.Encode(f));

                            // remove trailing comma on data set
                            sb.Remove(sb.ToString().LastIndexOf(','), 1);

                            // add delimiter
                            sb.Append("|");
                        }
                    });

                // remove trailing dataset delimiter
                if (EncodingType == EncodingType.Simple || EncodingType == EncodingType.Extended)
                    sb.Remove(sb.ToString().LastIndexOf(','), 1);
                else
                    sb.Remove(sb.ToString().LastIndexOf('|'), 1);
            }
            else 
            {
                // empty data set
                sb.Append('_');
            }

            return sb.ToString();
        }
    }
}
